package com.hc.jlxc_remote_sdk

import android.content.Context
import android.util.Log
import androidx.annotation.NonNull
import com.lz.RemoteSDK
import com.lz.tv.IApiCallback

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** JlxcRemoteSdkPlugin */
class JlxcRemoteSdkPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity

    private val TAG = "JlxcRemoteSdkPlugin"

    private lateinit var channel: MethodChannel

    private var context: Context? = null

    private var remoteSDK: RemoteSDK? = null

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "jlxc_remote_sdk")
        channel.setMethodCallHandler(this)
        this.context = flutterPluginBinding.applicationContext
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "init") {
            this.context?.let {
                RemoteSDK.init(it, object : IApiCallback {

                    override fun onSuccess(p0: RemoteSDK?) {
                        Log.e(TAG, "onSuccess: ${p0.toString()}")
                        remoteSDK = p0
                        result.success("")
                    }

                    override fun onFailed(p0: String?) {
                        Log.e(TAG, "onFailed: ${p0.toString()}")
                        result.error("500", p0, "$TAG  init")
                    }

                })
            }
        } else if (call.method == "getSN") {
            if (null == remoteSDK) {
                result.success("")
                return;
            }
            remoteSDK?.let {
                val sn = it.sn
                Log.e(TAG, "sn: $sn")
                result.success(sn)
            }
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
